package com.gkt.ec.cms.activity.controller;

import com.github.pagehelper.PageInfo;
import com.gkt.ec.cms.activity.AppConstant;
import com.gkt.ec.cms.activity.dao.OrganizationDao;
import com.gkt.ec.cms.activity.model.domain.CompanyActivityEntity;
import com.gkt.ec.cms.activity.model.domain.CustomerActivityEntity;
import com.gkt.ec.cms.activity.model.domain.MarketActivityEntity;
import com.gkt.ec.cms.activity.model.pojo.CustomerActivityVO;
import com.gkt.ec.cms.activity.model.pojo.SearchActivityVO;
import com.gkt.ec.cms.activity.service.ActivityService;
import com.gkt.ec.cms.activity.task.SendActivitySmsTaskManager;
import com.gkt.ec.cms.commons.enhance.AnonymousAccess;
import com.gkt.ec.cms.commons.enhance.Login;
import com.gkt.ec.cms.commons.model.domain.AdminUser;
import com.gkt.library.commons.shared.utils.DateUtils;
import com.gkt.library.commons.shared.utils.StringUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户活动添加controller
 */
@Controller
@AnonymousAccess
@RequestMapping(value = "/activity")
public class ActivityController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ActivityService activityService;
    @Autowired
    private SendActivitySmsTaskManager taskManager;

    @Autowired
    private OrganizationDao organizationDao;

    private final static String SEGMENT = "_";

    /**
     * 添加活动页
     */
    @RequestMapping(value = "/addActivity")
    public String addActivity(Map<String, Object> model, @Login AdminUser user) {
        model.put("activity", new MarketActivityEntity());
        return "/activityManager/addActivity";
    }

    /**
     * 添加活动页
     */
    @RequestMapping(value = "/editActivity")
    public String editActivity(Map<String, Object> model, @RequestParam Long id, @Login AdminUser user) {
        model.put("activity", activityService.getActivityDetail(id));

        return "/activityManager/addActivity";
    }

    /**
     * 保存活动
     */
    @RequestMapping(value = "/saveActivity", method = {RequestMethod.POST, RequestMethod.GET})
    public String saveActivity(MarketActivityEntity me, String selectCompanyIds, Map<String, Object> model, HttpServletRequest request, @Login AdminUser user) {

        me.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        me.setUpdateUser(user.getId());
        if (null == me.getId()) {
            me.setCreateTime(new Timestamp(System.currentTimeMillis()));
            me.setCreateUser(user.getId());
        }
        /**
         * 立即发送，设置短信发送时间为当前时间
         */
        if (me.getSmsSendType() == AppConstant.SmsSendType.IMMEDIATE) {
            me.setSmsSendTime(new Timestamp(System.currentTimeMillis()));
        }

        //保存活动之前，从任务队列移出当前任务
        if (null != me.getId()) {
            taskManager.cancelActivity(me.getId());
        }
        //保存活动
        log.info("saveActivity:" + me );
        activityService.saveActivity(me);

        Long activityId = me.getId();
        /**
         * 新增活动时，添加企业，保存活动信息时绑定企业
         *
         */
        if (StringUtils.isNotEmpty(selectCompanyIds)) {
            String[] companyIds = selectCompanyIds.split(",");
            for (String companyId : companyIds) {

                CompanyActivityEntity ca = new CompanyActivityEntity();
                ca.setActivityId(activityId);
                ca.setCompanyId(Long.parseLong(companyId.trim()));
                activityService.addCompanyActivity(ca);
            }
        }

        return "redirect:/activity/getActivityDetail?id=" + activityId;
    }

    /**
     * 绑定用户
     */
    @RequestMapping(value = "/bindCustomer")
    public String bindCustomer(CustomerActivityVO me, Map<String, Object> model, HttpServletRequest request, @Login AdminUser user) {
        log.info("bindCustomer==========" + me);

        Long activityId = me.getActivityId();
        //更新搜索条件
        MarketActivityEntity marketActivityEntity = new MarketActivityEntity();

        marketActivityEntity.setIsLimited(me.getIsLimited());
        marketActivityEntity.setLimitNumber(me.getLimitNumber());
        marketActivityEntity.setSearchAge(me.getSearchAge());
        marketActivityEntity.setSearchGender(me.getSearchGender());
        marketActivityEntity.setSearchMills(me.getSearchMills());
        marketActivityEntity.setSearchAgeLimit(me.getSearchAgeLimit());
        marketActivityEntity.setSearchStartTime(me.getSearchStartTime());
        marketActivityEntity.setSearchEndTime(me.getSearchEndTime());
        marketActivityEntity.setSearchVehicle(me.getSearchVehicles());
        marketActivityEntity.setSearchVehicleIds(me.getSearchVehicleIds());
        marketActivityEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        marketActivityEntity.setUpdateUser(user.getId());
        marketActivityEntity.setId(me.getActivityId());
        marketActivityEntity.setActivityTargetType(me.getActivityTargetType());
        log.info("bindCustomer marketActivityEntity==========" + marketActivityEntity);
        activityService.saveActivity(marketActivityEntity);

        //获取绑定的用户Map ，过滤用
        Map<String, Object> bindCustomerMap = getBindCustomerMap(activityId);

        //绑定用户
        String[] customerInfoArr = me.getCustomerInfos();
        for (String customerInfo : customerInfoArr) {
            String[] infos = customerInfo.split("_");
            String vehicleId = infos[0];
            String customId = infos[1];
            String cellphoneNumber = infos[2];
            String vehicleLicense = infos[3];
            String vehicleBrand = infos[4];
            String vehicleSeries = infos[5];
            //过滤已经添加过的用户或车辆
            if (null != bindCustomerMap.get(customId + SEGMENT + vehicleId)) {
                continue;
            }

            CustomerActivityEntity ca = new CustomerActivityEntity();
            ca.setActivityId(activityId);
            ca.setVehicleId(vehicleId);
            ca.setCustomId(customId);
            ca.setCustomerTel(cellphoneNumber);
            ca.setVehicleLicense(vehicleLicense);
            ca.setVehicleBrand(vehicleBrand);
            ca.setVehicleSeries(vehicleSeries);
            ca.setVerifyStatus(AppConstant.ActivitySmsVerifyStatus.NOT_VERIFY);
            ca.setSmsSendStatus(AppConstant.SendSmsStatus.UNSEND);
            ca.setCreateTime(new Timestamp(System.currentTimeMillis()));
            ca.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            ca.setCreateUser(user.getId());
            ca.setUpdateUser(user.getId());

            activityService.addCustomerActivity(ca);
        }

        return "redirect:/activity/getActivityView?isSubmit=1&id=" + activityId;
    }

    private Map<String, Object> getBindCustomerMap(Long activityId) {
        //获取选择的用户列表
        List<CustomerActivityEntity> customerList = activityService.queryAllCustomerActivity(activityId);
        Map<String, Object> bindCustomerMap = new HashMap<String, Object>();
        for (CustomerActivityEntity customer : customerList) {
            bindCustomerMap.put(customer.getCustomId() + SEGMENT + customer.getVehicleId(), customer.getCustomId());
        }
        return bindCustomerMap;
    }

    /**
     * 活动查询页
     */
    @RequestMapping(value = "/list")
    public String activityList(Map<String, Object> model) {
        return "/activityManager/activityList";
    }


    /**
     * 查询活动
     */
    @RequestMapping(value = "/queryActivityList")
    @ResponseBody
    public Object queryActivityList(SearchActivityVO searchCondition, HttpServletRequest request) {
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);

        searchCondition.setCurDate(DateUtils.formatDateTime(new Date()));
        log.info("searchCondition:" + searchCondition);
        PageInfo<MarketActivityEntity> pageInfo = activityService.queryActivityList(searchCondition, offset, max);

        for (MarketActivityEntity marketActivityEntity : pageInfo.getList()) {
            Date endDate = marketActivityEntity.getEndTime();
            Date sendTime = marketActivityEntity.getSmsSendTime();

            /**
             * activityStatus:"1":"未开始","2":"活动中","3":"已结束"
             */
            if (new Date().before(sendTime)) {
                marketActivityEntity.setActivityStatus("1");
                continue;
            }
            if (new Date().before(endDate) && new Date().after(sendTime)) {
                marketActivityEntity.setActivityStatus("2");
                continue;
            }
            if (new Date().after(endDate)) {
                marketActivityEntity.setActivityStatus("3");
                continue;
            }
        }

        return pageInfo;
    }

    /**
     * 活动详情页
     */
    @RequestMapping(value = "/getActivityDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public String getActivityDetail(Map<String, Object> model, @RequestParam Long id, @Login AdminUser user) {
        MarketActivityEntity activityEntity = activityService.getActivityDetail(id);
        model.put("activity", activityEntity);
        model.put("organizationName", organizationDao.getNameById(Long.valueOf(activityEntity.getActivityArea())));
        //获取选择的用户列表
        List<CustomerActivityEntity> customerList = activityService.queryAllCustomerActivity(id);
        List<String> customerIdList = new ArrayList<String>();
        for (CustomerActivityEntity ce : customerList) {
            customerIdList.add(ce.getCustomId());
        }
        if (CollectionUtils.isNotEmpty(customerIdList)) {
            model.put("selectCustomers", StringUtils.join(customerIdList.toArray(), ","));
        }
        log.info("model============" + model);
        return "/activityManager/activityDetail";
    }


    /**
     * 活动预览
     *
     * @param isSubmit 是否可以提交执行，从绑定用户页进去的页面可以执行 1：可执行
     */
    @RequestMapping(value = "/getActivityView", method = {RequestMethod.POST, RequestMethod.GET})
    public String getActivityView(Map<String, Object> model, @RequestParam Long id, String isSubmit, @Login AdminUser user) {
        MarketActivityEntity activityEntity = activityService.getActivityDetail(id);
        model.put("activity", activityEntity);
        model.put("organizationName", organizationDao.getNameById(Long.valueOf(activityEntity.getActivityArea())));
        if (StringUtils.isNotEmpty(isSubmit)) {
            model.put("isSubmit", "1".equals(isSubmit) ? "1" : "0");
        }
        return "/activityManager/activityView";
    }

    /**
     * 删除活动
     */
    @RequestMapping(value = "/delActivity", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object delActivity(Map<String, Object> model, @RequestParam Long id, @Login AdminUser user) {
        //删除活动之前，从任务队列移出当前任务
        taskManager.cancelActivity(id);

        HashMap paramMap = new HashMap();
        paramMap.put("updateUser", user.getId());
        paramMap.put("activityId", id);

        activityService.delActivity(paramMap);
        Map result = new HashMap(1);
        result.put("resultCode", "success");
        return result;
    }

    @RequestMapping(value = "/sendActivity")
    @ResponseBody
    public Object sendActivity(Map<String, Object> model, @RequestParam Long activityId, HttpServletRequest request) {
        taskManager.addActivity(activityService.getActivityDetail(activityId));
        Map result = new HashMap(1);
        result.put("resultCode", "success");
        return result;
    }

    /**
     * 解绑用户
     */
    @RequestMapping(value = "/cancelCustomerActivity")
    @ResponseBody
    public Object cancelCustomerActivity(Long activityId, String customerIds, Map<String, Object> model, HttpServletRequest request, @Login AdminUser user) {

        Map result = new HashMap(1);
        if (StringUtils.isEmpty(customerIds)) {
            result.put("resultCode", "error");
            return result;
        }
        String[] customerIdArr = customerIds.split(",");

        for (String customerId : customerIdArr) {
            CustomerActivityEntity ca = new CustomerActivityEntity();
            ca.setActivityId(activityId);
            ca.setCustomId(customerId);
            log.info(activityId + "===" + customerId);
            ca.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            ca.setUpdateUser(user.getId());
            activityService.cancelCustomerActivity(ca);
        }
        result.put("resultCode", "success");
        return result;
    }

    /**
     * 解绑企业
     */
    @RequestMapping(value = "/cancelCompanyActivity")
    @ResponseBody
    public Object cancelCompanyActivity(Long activityId, String companyIds, Map<String, Object> model, HttpServletRequest request, @Login AdminUser user) {

        Map result = new HashMap(1);
        if (StringUtils.isEmpty(companyIds)) {
            result.put("resultCode", "error");
            return result;
        }
        String[] companyIdArr = companyIds.split(",");
        for (String companyId : companyIdArr) {
            CompanyActivityEntity ca = new CompanyActivityEntity();
            ca.setActivityId(activityId);
            ca.setCompanyId(Long.parseLong(companyId));
            log.info("cancelCompanyActivity" + ca);
            activityService.cancelCompanyActivity(ca);
        }
        result.put("resultCode", "success");
        return result;
    }

    /**
     * 绑定企业
     */
    @RequestMapping(value = "/bindCompanyActivity")
    @ResponseBody
    public Object bindCompanyActivity(Long activityId, String companyIds, Map<String, Object> model, HttpServletRequest request, @Login AdminUser user) {

        Map result = new HashMap(1);
        if (StringUtils.isEmpty(companyIds)) {
            result.put("resultCode", "error");
            return result;
        }
        String[] companyIdArr = companyIds.split(",");
        for (String companyId : companyIdArr) {
            CompanyActivityEntity ca = new CompanyActivityEntity();
            ca.setActivityId(activityId);
            ca.setCompanyId(Long.parseLong(companyId));
            log.info("bindCompanyActivity" + ca);
            activityService.addCompanyActivity(ca);
        }
        result.put("resultCode", "success");
        return result;
    }

}
